// AI 对话页面 JavaScript 功能
class ChatApp {
    constructor() {
        this.initElements();
        this.bindEvents();
        this.setupMarkdown();
        this.setupHighlight();
        this.updateCharCount();
        this.initToast();
        this.currentStreamReader = null;
        this.isProcessing = false; // 防止重复提交的标志
    }

    initElements() {
        this.messageInput = document.getElementById('messageInput');
        this.sendBtn = document.getElementById('sendButton');
        this.clearBtn = document.getElementById('clearButton');
        this.chatMessages = document.getElementById('chatMessages');
        this.apiTypeSelect = document.getElementById('apiType');
        this.chatIdInput = document.getElementById('chatId');
        this.charCount = document.querySelector('.char-count');
        this.sendText = this.sendBtn ? this.sendBtn.querySelector('.send-text') : null;
        this.loadingSpinner = this.sendBtn ? this.sendBtn.querySelector('.loading-spinner') : null;
        
        // 调试信息
        console.log('Elements found:', {
            messageInput: !!this.messageInput,
            sendBtn: !!this.sendBtn,
            clearBtn: !!this.clearBtn,
            chatMessages: !!this.chatMessages,
            apiTypeSelect: !!this.apiTypeSelect,
            chatIdInput: !!this.chatIdInput,
            charCount: !!this.charCount
        });
    }

    bindEvents() {
        console.log('bindEvents called, elements:', {
            sendBtn: this.sendBtn,
            clearBtn: this.clearBtn,
            messageInput: this.messageInput
        });
        
        if (this.sendBtn) {
            this.sendBtn.addEventListener('click', () => this.sendMessage());
        }
        if (this.clearBtn) {
            this.clearBtn.addEventListener('click', () => this.clearChat());
        }
        if (this.messageInput) {
            this.messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            });
            this.messageInput.addEventListener('input', () => this.updateCharCount());
            
            // 自动调整输入框高度
            this.messageInput.addEventListener('input', () => this.autoResizeTextarea());
        }
    }

    setupMarkdown() {
        // 配置 marked.js
        if (typeof marked !== 'undefined') {
            marked.setOptions({
                highlight: function(code, lang) {
                    if (typeof hljs !== 'undefined' && lang && hljs.getLanguage(lang)) {
                        return hljs.highlight(code, { language: lang }).value;
                    }
                    return typeof hljs !== 'undefined' ? hljs.highlightAuto(code).value : code;
                },
                breaks: true,
                gfm: true
            });
        }
    }

    setupHighlight() {
        // 配置代码高亮
        if (typeof hljs !== 'undefined') {
            hljs.configure({
                languages: ['javascript', 'python', 'java', 'html', 'css', 'json', 'xml', 'sql', 'markdown']
            });
        }
    }

    updateCharCount() {
        const length = this.messageInput.value.length;
        this.charCount.textContent = `${length}/2000`;
        
        if (length > 1800) {
            this.charCount.style.color = '#e74c3c';
        } else if (length > 1500) {
            this.charCount.style.color = '#f39c12';
        } else {
            this.charCount.style.color = '#7f8c8d';
        }
    }

    autoResizeTextarea() {
        this.messageInput.style.height = 'auto';
        this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 120) + 'px';
    }

    initToast() {
        // 创建toast容器
        if (!document.getElementById('toast-container')) {
            const toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.className = 'toast-container';
            document.body.appendChild(toastContainer);
        }
    }

    showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        
        const icon = type === 'success' ? 'fas fa-check-circle' : 
                    type === 'error' ? 'fas fa-exclamation-circle' : 
                    'fas fa-info-circle';
        
        toast.innerHTML = `
            <i class="${icon}"></i>
            <span>${message}</span>
        `;
        
        const container = document.getElementById('toast-container');
        container.appendChild(toast);
        
        // 显示动画
        setTimeout(() => toast.classList.add('show'), 100);
        
        // 自动移除
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => container.removeChild(toast), 300);
        }, 3000);
    }

    async sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message || this.isProcessing) {
            if (!message) {
                this.showToast('请输入消息内容', 'error');
            }
            return;
        }

        if (message.length > 2000) {
            this.showToast('消息长度不能超过2000字符', 'error');
            return;
        }

        const chatId = this.chatIdInput.value.trim() || 'default';
        const apiType = this.apiTypeSelect.value;

        // 显示用户消息
        this.addMessage(message, 'user');
        this.messageInput.value = '';
        this.updateCharCount();
        this.autoResizeTextarea();

        // 设置处理状态
        this.setProcessing(true);

        try {
            if (apiType === 'stream') {
                await this.sendStreamMessage(message, chatId);
            } else {
                await this.sendSimpleMessage(message, chatId);
            }
            this.showToast('消息发送成功', 'success');
        } catch (error) {
            console.error('发送消息失败:', error);
            this.addMessage('发送消息失败，请重试', 'error');
            this.showToast('发送消息失败，请重试', 'error');
        } finally {
            this.setProcessing(false);
        }
    }

    async sendSimpleMessage(message, chatId) {
        const response = await fetch(`/openai/simple/chat?query=${encodeURIComponent(message)}&chat-id=${encodeURIComponent(chatId)}`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.text();
        this.addMessage(result, 'assistant');
    }

    async sendStreamMessage(message, chatId) {
        const response = await fetch(`/openai/stream/chat?query=${encodeURIComponent(message)}&chat-id=${encodeURIComponent(chatId)}`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        this.currentStreamReader = reader;
        
        const messageElement = this.addMessage('', 'assistant');
        const messageContent = messageElement.querySelector('.message-content');
        let fullContent = '';
        let buffer = '';

        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = new TextDecoder().decode(value);
                buffer += chunk;
                
                // 处理SSE格式的数据
                const lines = buffer.split('\n');
                buffer = lines.pop() || ''; // 保留最后一个不完整的行
                
                for (const line of lines) {
                    if (line.startsWith('data:')) {
                        const data = line.slice(5).trim(); // 移除'data:'前缀和空格
                        if (data && data !== '[DONE]') {
                            fullContent += data;
                            messageContent.innerHTML = this.renderMarkdown(fullContent);
                            this.scrollToBottom();
                        }
                    }
                }
            }
        } catch (error) {
            if (error.name !== 'AbortError') {
                throw error;
            }
        } finally {
            this.currentStreamReader = null;
        }
    }

    updateStreamingContent(contentElement, text, isFinal = false) {
        if (typeof marked !== 'undefined') {
            try {
                // 对于流式输出，我们需要处理不完整的Markdown
                let processedText = text;
                
                // 如果不是最终渲染，检查是否有未完成的代码块
                if (!isFinal) {
                    // 检查是否有未闭合的代码块
                    const codeBlockMatches = text.match(/```/g);
                    if (codeBlockMatches && codeBlockMatches.length % 2 === 1) {
                        // 有未闭合的代码块，暂时添加闭合标记
                        processedText = text + '\n```';
                    }
                }
                
                contentElement.innerHTML = marked.parse(processedText);
                
                // 对代码块进行语法高亮
                if (typeof hljs !== 'undefined') {
                    contentElement.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightElement(block);
                    });
                }
            } catch (error) {
                // 如果Markdown解析失败，回退到纯文本
                contentElement.textContent = text;
            }
        } else {
            contentElement.textContent = text;
        }
    }

    addMessage(content, type) {
        // 移除欢迎消息
        const welcomeMessage = this.chatMessages.querySelector('.welcome-message');
        if (welcomeMessage) {
            welcomeMessage.remove();
        }

        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        
        // 创建图标
        const icon = document.createElement('div');
        icon.className = 'message-icon';
        
        if (type === 'user') {
            icon.innerHTML = '👤'; // 用户图标
        } else if (type === 'assistant') {
            icon.innerHTML = '🤖'; // AI图标
        } else if (type === 'error') {
            icon.innerHTML = '⚠️'; // 错误图标
        }
        
        // 创建消息内容
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        
        if (type === 'user') {
            messageContent.textContent = content;
        } else {
            messageContent.innerHTML = this.renderMarkdown(content);
        }
        
        messageDiv.appendChild(icon);
        messageDiv.appendChild(messageContent);
        
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
        
        return messageDiv;
    }

    renderMarkdown(content) {
        if (typeof marked !== 'undefined') {
            const html = marked.parse(content);
            // 高亮代码块
            setTimeout(() => {
                if (typeof hljs !== 'undefined') {
                    this.chatMessages.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightElement(block);
                    });
                }
            }, 0);
            return html;
        }
        return content.replace(/\n/g, '<br>');
    }

    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'message assistant';
        errorDiv.innerHTML = `
            <div class="message-content" style="background: #fee; border-color: #fcc; color: #c33;">
                ❌ ${message}
            </div>
            <div class="message-time">${new Date().toLocaleTimeString()}</div>
        `;
        
        this.chatMessages.appendChild(errorDiv);
        this.scrollToBottom();
    }

    clearChat() {
        // 停止当前的流式请求
        if (this.currentStreamReader) {
            this.currentStreamReader.cancel();
            this.currentStreamReader = null;
        }
        
        // 清空消息并显示欢迎消息
        this.chatMessages.innerHTML = `
            <div class="welcome-message">
                <i class="fas fa-robot welcome-icon"></i>
                <h3>欢迎使用 Spring AI 智能助手</h3>
                <p>我是您的AI助手，可以帮您解答问题、处理文档、进行智能对话。</p>
                <p>请在下方输入您的问题，我会尽力为您提供帮助。</p>
                <div class="welcome-features">
                    <div class="feature-item">
                        <i class="fas fa-comments"></i>
                        <span>智能对话</span>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-file-alt"></i>
                        <span>文档处理</span>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-search"></i>
                        <span>知识检索</span>
                    </div>
                    <div class="feature-item">
                        <i class="fas fa-lightbulb"></i>
                        <span>创意助手</span>
                    </div>
                </div>
            </div>
        `;
        
        // 重置处理状态
        this.setProcessing(false);
        this.showToast('对话已清空', 'info');
    }

    setProcessing(processing) {
        this.isProcessing = processing;
        
        if (this.sendBtn) {
            this.sendBtn.disabled = processing;
            
            if (this.sendText && this.loadingSpinner) {
                if (processing) {
                    this.sendText.style.display = 'none';
                    this.loadingSpinner.style.display = 'inline-block';
                } else {
                    this.sendText.style.display = 'inline';
                    this.loadingSpinner.style.display = 'none';
                }
            }
            
            // 更新按钮文本
            if (processing) {
                this.sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 发送中...';
            } else {
                this.sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 发送';
            }
        }
    }

    scrollToBottom() {
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 确保只创建一个ChatApp实例
    if (!window.chatApp) {
        window.chatApp = new ChatApp();
    }
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (window.chatApp && window.chatApp.currentStreamReader) {
        window.chatApp.currentStreamReader.cancel();
    }
});